package com.tenement.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tenement.entity.Role;
import com.tenement.mapper.RoleMapper;
import com.tenement.mapper.UserRoleMapper;
import com.tenement.service.RoleMenuService;
import com.tenement.service.RoleService;
import com.tenement.service.UserRoleService;
import com.tenement.vo.QueryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.tenement.entity.table.RoleTableDef.ROLE;

/**
 *  服务层实现。
 *
 * @author BertXie
 * @since 1.0.1
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper roleMapper;

    private final RoleMenuService roleMenuService;

    private final UserRoleService userRoleService;

    @Override
    public Page<Role> list(QueryVo queryVo) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .from(ROLE)
                .where(ROLE.DESCRIPTION.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord()))
                        .or(ROLE.NAME.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord())))
                        .or(ROLE.PERMISSION_CODE.like(queryVo.getKeyWord(), StrUtil.isNotEmpty(queryVo.getKeyWord())))
                )
                .and(ROLE.STATUS.eq(queryVo.getStatus(), queryVo.getStatus() != -1))
                .orderBy(ROLE.SORT_ORDER,false)
                .orderBy(ROLE.UPDATE_TIME,false);
        return roleMapper.paginate(queryVo.getPage(),queryVo.getSize(),queryWrapper);
    }

    @Override
    public int remove(List<Long> ids) {
        if (ids != null && ids.size() > 0) {
            int rows = roleMapper.deleteBatchByIds(ids);
            if (rows > 0) {
                //TODO 删除角色对应的权限,以及对应的用户角色
                roleMenuService.remove(ids);
                userRoleService.remove(ids);
            }
            return rows;
        }
        return 0;
    }


}
